/**   
 *    
 * 项目名称：a_yongan   
 * 类名称：ProcessProcessServiceImpl   
 * 类描述：   
 * 创建人：liubo   
 * 创建时间：2018年6月18日 下午2:10:43    
 * 修改时间：2018年6月18日 下午2:10:43   
 * 修改备注：   
 * @version    
 *    
 */
package com.yongan.workflow.service.impl;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.workflow.dao.FlowDetailsDao;
import com.yongan.workflow.dao.FlowInfoDao;
import com.yongan.workflow.entity.FlowDetails;
import com.yongan.workflow.entity.FlowInfo;
import com.yongan.workflow.service.FlowInfoService;

/**
 * @author liubo
 * 
 */
@Service
public class FlowInfoServiceImpl implements FlowInfoService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private FlowInfoDao flowInfoDao;
	@Autowired
	private FlowDetailsDao flowDetailsDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";

	@Override
	public List<FlowInfo> getFlowInfoList(int offset, int limit) {
		List<FlowInfo> list = flowInfoDao.queryAll(offset, limit);
		for(FlowInfo fi:list){
			fi.setDetails(flowDetailsDao.queryAllByTopId(fi.getFlowInfoId()));
		}
		return list;
	}

	@Override
	public FlowInfo getFlowInfoById(String flowInfoId) {
		List<FlowInfo> flowInfos = flowInfoDao.queryById(flowInfoId);
		FlowInfo flowInfors = null;
		for(FlowInfo flowInfo:flowInfos){
			if(flowInfo.getFlowInfoUse().equals("true")){
				flowInfo.setDetails(flowDetailsDao.queryAllByTopId(flowInfoId));
				flowInfors =  flowInfo;
			}
		}
		return flowInfors;
	}
	
	@Override
	public FlowInfo getFlowInfoByUrl(String flowInfoId,String type) {
		
		List<FlowInfo> flowInfos = flowInfoDao.queryByUrl(flowInfoId);
		FlowInfo flowInfors = null;
		for(FlowInfo flowInfo:flowInfos){
			if(flowInfo.getFlowInfoUse().equals("true")){
				if(flowInfoId.equals("processprocess")){
					if(flowInfo.getFlowInfoType().equals(type)){
						flowInfo.setDetails(flowDetailsDao.queryAllByTopId(flowInfo.getFlowInfoId()));
						flowInfors =  flowInfo;
					}
				}else{
					flowInfo.setDetails(flowDetailsDao.queryAllByTopId(flowInfo.getFlowInfoId()));
					flowInfors =  flowInfo;
				}
			}
		}
		return flowInfors;
	}

	@Transactional
	@Override
	public Execution executeFlowInfo(FlowInfo flowInfo,
			String flowInfoId, String md5) throws UserException {
		if (md5 == null || !md5.equals(getMD5(flowInfoId))) {
			// throw new UserException("user data rewrite");
		}
		try {
			if (flowInfo == null) {
				//FlowInfo pp = flowInfoDao.queryById(flowInfoId);
				int deleteDetails;
				int deleteCount;
				deleteCount = flowInfoDao.deleteFlowInfo(flowInfoId);
				deleteDetails = flowDetailsDao.deleteAllByTopId(flowInfoId);
				if (deleteCount <= 0 & deleteDetails <= 0) {
					throw new UserException("delete failed");
				} else {
					return new Execution(flowInfoId, UserStatEnum.SUCCESS);
				}
			} else if ((flowInfoId.equals(""))) {
				String topId = UUID.randomUUID().toString();
				flowInfo.setFlowInfoId(topId);
				int addCount = flowInfoDao.insertFlowInfo(flowInfo);
				List<FlowDetails> details = flowInfo.getDetails();
				Boolean isDetails = false;
				for (FlowDetails detail : details) {
					detail.setFlowDetailsId(UUID.randomUUID().toString());;
					detail.setFlowInfoId(topId);
					int detailAdd = flowDetailsDao.insertFlowDetails(detail);
					if (detailAdd <= 0) {
						isDetails = true;
					}
				}	
				if (addCount <= 0 & isDetails) {
					throw new UserException("add failed");
				} else {
					return new Execution(flowInfo.getFlowInfoId(),UserStatEnum.SUCCESS);
				}
			} else if (!(flowInfoId.equals(""))) {
				int updateCount = flowInfoDao.updateFlowInfo(flowInfo);
				List<FlowDetails> details = flowInfo.getDetails();
				//int oldDell = flowDetailsDao.deleteAllByTopId(flowInfoId);
				Boolean isDetails = false;
				for (FlowDetails detail : details) {
					if(detail.getFlowDetailsId().equals("")){
						detail.setFlowDetailsId(UUID.randomUUID().toString());;
						detail.setFlowInfoId(flowInfoId);
						int detailsCount = flowDetailsDao.insertFlowDetails(detail);
						if (detailsCount <= 0) {
							isDetails = true;
						}
					}else{
						int upc = flowDetailsDao.updateFlowDetails(detail);
						if (upc <= 0) {
							isDetails = true;
						}
					}
					
				}
				if (updateCount <= 0 & isDetails /*& oldDell<=0*/) {
					throw new UserException("update failed");
				} else {
					return new Execution(flowInfoId, UserStatEnum.SUCCESS);
				}
			} else {
				throw new UserException("parameter error");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}

	public int getCount() {
		return flowInfoDao.queryCount();
	}

	private String getMD5(String Id) {
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

}
